package cn.lbwfree.web.repository.impl;

import cn.lbwfree.web.entity.Book;
import cn.lbwfree.web.entity.BookCase;
import cn.lbwfree.web.repository.BookRepository;
import cn.lbwfree.web.utils.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {

    @Override
    public List<Book> findAll(int index ,int limit) {
        System.out.println("BookRepositoryImpl success");
        Connection connection = JDBCTools.getConnection();
        String sql = "Select * from book,bookcase where book.bookcaseid=bookcase.id limit ?,?";
        PreparedStatement preparedStatement =null;
        ResultSet resultSet= null;
        List<Book> list =new ArrayList<Book>();
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, index);
            preparedStatement.setInt(2, limit);
            resultSet = preparedStatement.executeQuery();
            BookCase bookCase=null;
            Book book=null;
            while(resultSet.next())
            {
                bookCase = new BookCase(resultSet.getInt(9),resultSet.getString(10));
                book = new Book(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4),resultSet.getInt(5),resultSet.getDouble(6),bookCase);
                list.add(book);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, preparedStatement, resultSet);
        }
        Iterator iterator = list.iterator();
        while (iterator.hasNext())
        {
            System.out.println(iterator.next());
        }
        return list;
    }

    @Override
    public int count() {
        Connection connection = JDBCTools.getConnection();
        String sql = "select count(*) from book,bookcase where book.bookcaseid = bookcase.id";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        int count = 0;
        try {
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                count = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return count;
    }
}
